// 折线图对象组件

var H5ComponentPolyline = function(name, cfg) {
	var component = new H5ComponentBase(name, cfg);

	//绘制网格线
	var w = cfg.width;
	var h = cfg.height;

	//加入一个画布（网格线背景）
	var cns = document.createElement('canvas');
	var ctx = cns.getContext('2d');
	cns.width = ctx.widht = w;
	cns.height = ctx.height = h;
	component.append(cns);

	//水平网格线 100份 --> 10份
	var step = 10;
	ctx.beginPath();
	ctx.lineWidth = 1;
	ctx.strokeStyle = '#AAAAAA';
	for(var i = 0; i < step + 1; i++) {
		var y = (h/step) * i;
		ctx.moveTo(0, y);
		ctx.lineTo(w, y);
	}

	//绘制垂直网格线 根据项目数据去分
	step = cfg.data.length + 1;
	for(var i = 0; i < step + 1; i++) {
		var x = (w/step) * i;
		ctx.moveTo(x, h);
		ctx.lineTo(x, 0);

		//插入项目名称DOM元素
		var text = $('<div class="text"></div>');
		var text_w = (w/step)/2 >> 0;

		text.css('width', text_w).css('left', x/2 + text_w/2).css('transitionDelay', .1*i+2+'s');
		// text.css('left', (w/step)/4);
		if(cfg.data[i]) {
			text.text(cfg.data[i][0]);
			component.append(text);
		}
	}

	ctx.stroke();

	//加入画布 (数据层)
	var cns = document.createElement('canvas');
	var ctx = cns.getContext('2d');
	cns.width = ctx.widht = w;
	cns.height = ctx.height = h;
	component.append(cns);

	/**
	 * 绘制折线以及对应到数据和阴影
	 * @param  {[float] per 0到1之间的数据，会根据这个值绘制最终数据对应到中间状态}
	 * @return {[]} 
	 */
	var draw = function(per) {
		//清空画布
		ctx.clearRect(0, 0, w, h);

		//绘制数据
		ctx.beginPath();
		ctx.lineWidth = 3;
		ctx.strokeStyle = '#ff8878';

		var x = 0;
		var y = 0;
		var row_w = w / step;
		for (var i = 0, len = cfg.data.length; i < len; i++) {
			x = (row_w) * (i+1);
			y = (1 - cfg.data[i][1] * per) * h;

			ctx.moveTo(x + 4, y);
			ctx.arc(x, y, 4, 0, 2 * Math.PI);
			ctx.fillStyle = cfg.data[i][2] ? cfg.data[i][2] : '#595959';
			ctx.fillText(((cfg.data[i][1] * 100)>>0) + '%', x - 10, y - 15);
		}

		//连线
		ctx.moveTo(w / step, (1 - cfg.data[0][1] * per) * h);
		for(var i = 0, len = cfg.data.length; i < len; i++) {
			x = (row_w) * (i+1);
			y = (1 - cfg.data[i][1] * per) * h;

			ctx.lineTo(x, y);
		}

		ctx.stroke();

		//绘制阴影
		ctx.strokeStyle = 'rgba(244, 67, 54, 0)';
		ctx.lineTo(x, h);
		ctx.lineTo(row_w, h);
		ctx.fillStyle = 'rgba(244, 67, 54, .3)';
		ctx.fill();

		ctx.stroke();
	}

	


	component.on('onLoad', function() {
		//折线图生长动画
		var s = 0;
		for(var i = 0; i <= 100; i++){
			setTimeout(function() {
				s += 0.01;
				draw(s);
			}, 10*i + 1000);
		}
	});

	component.on('onLeave', function() {
		//折线图退场动画
		var s = 1;
		for(var i = 0; i <= 100; i++){
			setTimeout(function() {
				s -= 0.01;
				draw(s);
			}, 10*i);
		}
	});


	return component;
}